package internal

import (
	"context"
	"net/http"
	"os"
	"time"

	"gitee.com/zhuoyue6/wecom_msg/config"
	"github.com/gin-gonic/gin"
)

// GetGlobalRouter 获取全局路由器
func GetGlobalRouter() *gin.Engine {
	if config.GlobalConfig.IsDebug {
		gin.SetMode(gin.DebugMode)
	} else {
		gin.SetMode(gin.ReleaseMode)
	}
	r := gin.New()
	r.Use(gin.Recovery(), SignatureMiddleware())

	// 健康检查
	r.GET("sys/health", func(c *gin.Context) {
		c.JSON(http.StatusOK, gin.H{
			"status":    "ok",
			"timestamp": time.Now().Format(time.RFC3339),
			"environment": map[string]string{
				"function_name":    os.Getenv("FC_FUNCTION_NAME"),
				"function_handler": os.Getenv("FC_FUNCTION_HANDLER"),
			},
		})
	})

	// 配置信息
	r.GET("sys/config", func(c *gin.Context) {
		c.JSON(http.StatusOK, gin.H{
			"code": 0,
			"msg":  "success",
			"data": config.GlobalConfig,
		})
	})

	// 创建用户同步器和消息发送器
	ctx := context.Background()
	userSync := NewUserSyncSynchronizer(ctx)
	messageSender := NewMessageSender(ctx)

	// 同步用户数据API
	r.POST("api/sync/users", userSync.SyncUsersAPI)

	// 消息发送API - 按消息类型区分路由
	messageGroup := r.Group("api/message")
	{
		// 发送Markdown消息
		messageGroup.POST("markdown", createMessageHandler(messageSender, MessageTypeMarkdown))
		// 发送文本消息
		messageGroup.POST("text", createMessageHandler(messageSender, MessageTypeText))
	}

	return r
}

// createMessageHandler 创建消息处理函数
func createMessageHandler(messageSender *MessageSender, messageType MessageType) gin.HandlerFunc {
	return func(c *gin.Context) {
		var req MessageRequest
		if err := c.ShouldBindJSON(&req); err != nil {
			c.JSON(http.StatusBadRequest, MessageResponse{
				Code:    400,
				Message: "请求参数错误",
				Data:    gin.H{"error": err.Error()},
			})
			return
		}
		messageSender.sendMessageCommon(c, string(messageType), &req)
	}
}
